import { Ctrl, IDot, dot, dot_in_circle, line_circle_intersection, manhattan } from "./TriCir";

export class CanvasCtrl extends Ctrl {
  pointer_offset: IDot = dot(0, 0);
  hover = 0;
  pressed = false;
  pointerdown_pos: number[] = [0, 0];
  pointerdown(x: number, y: number) {
    this.pointerdown_pos = [x, y];
    this.pressed = !0;
    this.pointer_offset.x = x - this.dot.x;
    this.pointer_offset.y = y - this.dot.y;
  }
  pointermove(x: number, y: number) {
    const hover = dot_in_circle(this.dot, this.radius * 1.5, { x, y });
    if (this.pressed) {
      x -= this.pointer_offset.x;
      y -= this.pointer_offset.y;
      const { o, r } = this.tri;
      const [a] = line_circle_intersection(o.x, o.y, r, x, y, this.watch.x, this.watch.y)
        .sort((a, b) => manhattan(this.watch.x, this.watch.y, ...b) - manhattan(this.watch.x, this.watch.y, ...a));
      this.dot.x = a[0];
      this.dot.y = a[1];
    } else if (!this.hover && hover) {
      this.hover = 1;
    } else if (this.hover && !hover) {
      this.hover = 0;
    }
  }
  pointerup(x: number, y: number) {
    this.pressed = !1;
  }
  render(ctx: CanvasRenderingContext2D) {
    const black = this.hover ? '#000000FF' : '#000000';
    const white = this.hover ? '#FFFFFFFF' : '#FFFFFF';
    const r = this.hover ? this.radius * 1.5 : this.radius;
    ctx.lineWidth = 1;
    ctx.strokeStyle = black;
    ctx.fillStyle = white;
    ctx.setLineDash([]);
    if (this.hover) {
      ctx.beginPath();
      ctx.moveTo(this.watch.x, this.watch.y);
      ctx.lineTo(this.dot.x, this.dot.y);
      ctx.stroke();
    }
    ctx.beginPath();
    ctx.ellipse(this.dot.x, this.dot.y, r, r, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    ctx.lineWidth = 3;
    ctx.strokeStyle = white;
    ctx.fillStyle = black;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.strokeText(this.name, this.dot.x, this.dot.y);
    ctx.fillText(this.name, this.dot.x, this.dot.y);
  }
}
